<?php
define('IN_IA', true);
/**
 * 原生支付（扫码支付）及公众号支付的异步回调通知
 * 说明：需要在native.php或者jsapi.php中的填写回调地址。例如：http://www.xxx.com/wx/notify.php
 * 付款成功后，微信服务器会将付款结果通知到该页面
 */
header('Content-type:text/html; Charset=utf-8');

$addons_dir = str_replace("\\", '/', dirname(dirname(__FILE__)));
require_once $addons_dir . '/../data/config.php';
require_once $addons_dir . '/../framework/class/loader.class.php';
require_once $addons_dir . '/../framework/function/global.func.php';
require_once $addons_dir . '/../framework/class/db.class.php';
require_once $addons_dir . '/../framework/function/pdo.func.php';
require_once $addons_dir . '/../framework/function/file.func.php';
require_once $addons_dir . '/yq_haircircle/common.php';
require_once $addons_dir . '/yq_haircircle/inc/mobile/dofx.inc.php';
global $_W;
$_W['config'] = $config;
$fx_log = '../../attachment/upgradelog/';
if (!file_exists($fx_log)) {
    mkdirs($fx_log);
}
$fx_log .= (date('Y-m-d') . '.txt');

$pay_setting = cmf_get_option('pay_setting');

$jsweixinpay = isset($pay_setting['jsweixinpay']) ? $pay_setting['jsweixinpay'] : false;
if (!$jsweixinpay) {
    file_put_contents($fx_log,'pay setting error'.PHP_EOL,FILE_APPEND);
    exit;
}

$mchid = $jsweixinpay['mchid'];          //微信支付商户号 PartnerID 通过微信支付商户资料审核后邮件发送
$appid = $jsweixinpay['appid'];  //公众号APPID 通过微信支付商户资料审核后邮件发送
$apiKey = $jsweixinpay['apikey'];   //https://pay.weixin.qq.com 帐户设置-安全设置-API安全-API密钥-设置API密钥
$wxPay = new WxpayService($mchid, $appid, $apiKey);

$result = $wxPay->notify();
if (!$result) {
    file_put_contents($fx_log,'pay check error'.PHP_EOL,FILE_APPEND);exit;
}

pdo_begin();

try {
    $params = $result;

    $order = pdo_get('yq_haircircle_upgrade_order', array('order_sn' => $params['out_trade_no']));
    if (empty($order)) {
        file_put_contents($fx_log,'订单不存在'.PHP_EOL,FILE_APPEND);exit;
        exit;
    }
    if ($order['is_true']) {
        echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        exit;
    }
    //上线要加上
//    if ($params['total_fee'] != $order['payprice'] * 100) {
//        file_put_contents($fx_log,'费用不正确'.PHP_EOL,FILE_APPEND);exit;
//        exit;
//    }

    $res = pdo_update('yq_haircircle_upgrade_order', array('paytime' => time(), 'is_true' => 1), array('order_sn' => $order['order_sn']));
    if (empty($res)) {
        file_put_contents($fx_log,'更新订单状态失败'.PHP_EOL,FILE_APPEND);exit;
        pdo_rollback();
        die;
    }
// 修改会员等级
    $res = pdo_update('yq_haircircle_users', array('user_level' => 1), array('id' => $order['user_id']));
    if (empty($res)) {
        file_put_contents($fx_log,'更新用户等级失败'.PHP_EOL,FILE_APPEND);exit;
        pdo_rollback();
        die;
    }
} catch (\Exception $e) {
    file_put_contents($fx_log,'抛出异常：' . $e->getMessage());
    pdo_rollback();
    die;
}

pdo_commit();

doUpgradeFx($order);
//结束通知
echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
exit;

class WxpayService
{
    protected $mchid;
    protected $appid;
    protected $apiKey;
    protected $fxlog;
    public function __construct($mchid, $appid, $key)
    {
        $this->mchid = $mchid;
        $this->appid = $appid;
        $this->apiKey = $key;
        $this->fxlog = '../../attachment/upgradelog/';
        if (!file_exists($this->fxlog)) {
            mkdirs($this->fxlog);
        }
        $this->fxlog .= (date('Y-m-d') . '.txt');
    }

    public function notify()
    {
        $config = array(
            'mch_id' => $this->mchid,
            'appid' => $this->appid,
            'key' => $this->apiKey,
        );
        $postStr = file_get_contents('php://input');
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        if ($postObj === false) {
            file_put_contents($this->fxlog,'parse xml error'.PHP_EOL,FILE_APPEND);exit;
            return false;
        }
        if ($postObj->return_code != 'SUCCESS') {
            file_put_contents($this->fxlog,$postObj->return_msg.PHP_EOL,FILE_APPEND);exit;
            return false;
        }
        if ($postObj->result_code != 'SUCCESS') {
            file_put_contents($this->fxlog,$postObj->err_code.PHP_EOL,FILE_APPEND);exit;
            return false;
        }
        $arr = (array)$postObj;
        unset($arr['sign']);
        if (self::getSign($arr, $config['key']) == $postObj->sign) {
            return $arr;
        }
    }

    /**
     * 获取签名
     */
    public static function getSign($params, $key)
    {
        ksort($params, SORT_STRING);
        $unSignParaString = self::formatQueryParaMap($params, false);
        $signStr = strtoupper(md5($unSignParaString . "&key=" . $key));
        return $signStr;
    }

    protected static function formatQueryParaMap($paraMap, $urlEncode = false)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if (null != $v && "null" != $v) {
                if ($urlEncode) {
                    $v = urlencode($v);
                }
                $buff .= $k . "=" . $v . "&";
            }
        }
        $reqPar = '';
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }
        return $reqPar;
    }
}
